//新增商品自定义商品部分
import React, { useState, useMemo, useImperativeHandle, forwardRef, useEffect } from "react";
import CommonTable from "@/pages/OrderModule/common/components/CommonTable/components/CommonTable";
import CommonImgsLoad from "@/components/CommonImgsLoad";
import { getZJFStorePage } from "../service";
import { Button, Popconfirm, Input, InputNumber, Select, Tooltip } from "antd";
import styles from "./index.module.less";
import { isEmpty, find, cloneDeep, findIndex } from "lodash";

const { TextArea } = Input;
const { Option } = Select;

//默认的商品
const initGood = {
	goodsImage: "",
	goodsName: "",
	color: "",
	size: "",
	goodsNum: "",
	storeId: "",
	storeName: "",
	shopCode: "",
	goodsPrice: "0.01"
};

const CustomizeGoodsModal = ({}, ref) => {
	const [data, setData] = useState([{ ...initGood }]); //表格数据
	const [selectData, setSelectData] = useState([]); //供应商和档口号下拉
	const [loading, setLoading] = useState(false); //loading

	const dataWithKeys = useMemo(() => {
		return data.map((item, index) => ({
			...item,
			key: index // 或者使用更稳定的唯一ID
		}));
	}, [data]);

	//父组件改变地图的定位
	useImperativeHandle(ref, () => ({
		customizeList: data
	}));

	//获取供应商下拉
	const getSelectData = async (val, code) => {
		setLoading(true);
		const { success, data = {} } = await getZJFStorePage({
			[code]: val,
			state: 1,//正常未删除
			industrialBeltFlag: INDUSTRIAL_BELT_FLAG
		});
		if (success) {
			const { records = [] } = data;
			setSelectData(records);
		}
		setLoading(false);
	};

	//图片上传
	const handleImgUpload = (val, record, index, code) => {
		const arr = cloneDeep(data);
		arr[index][code] = val;
		setData(arr);
	};

	//输入框的失去焦点改变
	const handleCommonBlur = async (val, text, record, index, code) => {
		const arr = cloneDeep(data);
		arr[index][code] = val;
		setData(arr);
	};

	//供应商下拉选择
	const handleChange = (e, record, index, code) => {
		const arr = cloneDeep(data);
		const obj = find(selectData, [[code], e]);
		arr[index].storeId = obj.storeId;
		arr[index].storeName = obj.storeName;
		arr[index].shopCode = obj.shopCode;
		setData(arr);
	};

	//新增商品
	const handleAddGood = () => {
		const arr = cloneDeep(data);
		arr.push({
			...initGood
		});
		setData(arr);
	};

	//删除
	const handleDeleteItems = (record, index) => {
		const arr = cloneDeep(data);
		arr.splice(index, 1);
		setData(arr);
	};

	const tableColumns = [
		{
			title: "序号",
			dataIndex: "index",
			key: "index",
			width: 60,
			render: (t, r, i) => i + 1
		},
		{
			title: "图片（非必填）",
			dataIndex: "goodsImage",
			key: "goodsImage",
			width: 100,
			render: (t, r, i) => (
				<>
					<CommonImgsLoad handleOk={val => handleImgUpload(val, r, i, "goodsImage")} className="small" img={t} />
				</>
			)
		},
		{
			title: <span className={styles.labelReqire}>商品名称</span>,
			dataIndex: "goodsName",
			key: "goodsName",
			width: 120,
			render: (t, r, i) => (
				<>
					<Input
						value={t ? t : undefined}
						onChange={e => handleCommonBlur(e.target.value, t, r, i, "goodsName")}
						maxLength={100}
						placeholder="请输入商品名称"
					/>
				</>
			)
		},
		{
			title: "颜色",
			dataIndex: "color",
			key: "color",
			width: 100,
			render: (t, r, i) => (
				<>
					<TextArea
						onChange={e => handleCommonBlur(e.target.value, t, r, i, "color")}
						maxLength={100}
						value={t}
						placeholder="请输入颜色"
					/>
				</>
			)
		},
		{
			title: "尺码",
			dataIndex: "size",
			key: "size",
			width: 100,
			render: (t, r, i) => (
				<>
					<TextArea
						onChange={e => handleCommonBlur(e.target.value, t, r, i, "size")}
						maxLength={100}
						value={t}
						placeholder="请输入尺码"
					/>
				</>
			)
		},
		{
			title: <span className={styles.labelReqire}>商品数量</span>,
			dataIndex: "goodsNum",
			key: "goodsNum",
			width: 100,
			render: (t, r, i) => (
				<>
					<InputNumber
						onBlur={e => handleCommonBlur(e.target.value, t, r, i, "goodsNum")}
						onChange={e => handleCommonBlur(e, t, r, i, "goodsNum")}
						precision={0}
						min={1}
						max={999999}
						setp={1}
						value={t}
						placeholder="请输入商品数量"
					/>
				</>
			)
		},
		{
			title: <span className={styles.labelReqire}>供应商</span>,
			dataIndex: "storeId",
			key: "storeId",
			width: 100,
			render: (t, r, i) => (
				<>
					<Select
						showSearch
						placeholder="请选择供应商"
						defaultActiveFirstOption={false}
						showArrow={false}
						filterOption={false}
						dropdownMatchSelectWidth={false}
						onSearch={e => getSelectData(e, "storeName")}
						onChange={e => handleChange(e, r, i, "storeId")}
						value={t ? t : undefined}
						style={{ width: 90 }}
						notFoundContent={loading ? "加载中..." : "暂无数据"}
					>
						{options}
					</Select>
				</>
			)
		},
		{
			title: "档口号",
			dataIndex: "shopCode",
			key: "shopCode",
			width: 120,
			render: (t, r, i) => (
				<>
					<Select
						showSearch
						placeholder="请选择档口号"
						defaultActiveFirstOption={false}
						showArrow={false}
						filterOption={false}
						dropdownMatchSelectWidth={false}
						onSearch={e => getSelectData(e, "shopCode")}
						onChange={e => handleChange(e, r, i, "shopCode")}
						value={t || null}
						style={{ width: 90 }}
						notFoundContent={loading ? "加载中..." : "暂无数据"}
					>
						{options2}
					</Select>
				</>
			)
		},
		{
			title: <span className={styles.labelReqire}>采购价</span>,
			dataIndex: "goodsPrice",
			key: "goodsPrice",
			width: 100,
			render: (t, r, i) => (
				<>
					<InputNumber
						// onBlur={e => handleCommonBlur(e.target.value, t, r, i, "goodsPrice")}
						onChange={e => handleCommonBlur(e, t, r, i, "goodsPrice")}
						precision={2}
						min={0.01}
						max={999999.99}
						value={t}
						placeholder="请输入采购价"
					/>
				</>
			)
		},
		{
			title: "操作",
			width: 120,
			render: (t, r, i) => {
				return (
					<>
						<Popconfirm title="确定删除?" onConfirm={() => handleDeleteItems(r, i)} okText="确定" cancelText="取消">
							<Button type="link" size="small">
								删除
							</Button>
						</Popconfirm>
					</>
				);
			}
		}
	];

	//供应商下拉
	const options =
		!isEmpty(selectData) &&
		selectData.map(d => (
			<Option value={d.storeId} key={d.storeId} label={d.storeName}>
				<Tooltip title={d.storeName}>{d.storeName}</Tooltip>
			</Option>
		));

	//供应商下拉
	const options2 =
		!isEmpty(selectData) &&
		selectData
			.filter(item => item.shopCode)
			.map(d => (
				<Option value={d.shopCode} key={d.storeId} label={d.shopCode}>
					<Tooltip title={d.shopCode ? `${d.shopCode}` : ""}>{d.shopCode ? `${d.shopCode}` : ""}</Tooltip>
				</Option>
			));

	return (
		<div>
			<Button onClick={handleAddGood}>新增自定义商品</Button>
			<p className={styles.customizeText}>添加的自定义商品，不管在自发还是代发，都是走拿货采购流程，不需要校验库存</p>
			<CommonTable columns={tableColumns} dataSource={dataWithKeys} pagination={false} scroll={{ y: 500 }} rowKey={"key"} />
		</div>
	);
};

export default forwardRef(CustomizeGoodsModal);
